package au.com.handsunited.model.message;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import au.com.handsunited.model.BaseEntity;
import au.com.handsunited.model.MotherOfAllEntities;

/**
 * @author arunda
 *
 */
public class MessageBoard extends MotherOfAllEntities implements Comparable<MessageBoard> {

	private static Logger logger = LoggerFactory.getLogger(MessageBoard.class);

	private SortedSet<Message> messages;


	/**
	 *
	 */
	public MessageBoard() {
		super();
		messages = new TreeSet<Message>();
	}

	/**
	 *
	 * @param message
	 */
	public void addMessage(Message message) {
		message.setMessageBoard(this);
		if (messages == null) {
			messages = new TreeSet<Message>();
		}
		messages.add(message);
	}


	/**
	 *
	 * @param message
	 */
	public void deleteMessage(Message message) {
		if (messages != null) {
			messages.remove(message);
		}
	}

	public SortedSet<Message> getMessages() {

		if (messages == null) {
			messages = new TreeSet<Message>();
		}
		return messages;
	}

	public List<Message> getUnreadMessages() {
		List<Message> unreadMessages = new ArrayList<Message>();

		for (Message message : messages) {
			if (message.isUnread()) {
				unreadMessages.add(message);
			}
		}

		return unreadMessages;
	}

	public boolean hasUnreadMessages() {
		return !getUnreadMessages().isEmpty();
	}

	public int getNumberOfMessages() {
		return messages.size();
	}

	public int getNumberOfUnreadMessages() {

		return getUnreadMessages().size();
	}

	public List<Message> getMessagesFrom (BaseEntity poster) {
		List<Message> messagesFromPoster = new ArrayList<Message>();

		for (Message message : messages) {
			if (message.getPoster().equals(poster)) {
				messagesFromPoster.add(message);
			}
		}
		return messagesFromPoster;
	}

	/**
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	@Override
	public int compareTo(MessageBoard messageBoard) {
		return getDateCreated().compareTo(messageBoard.getDateCreated());
	}

}
